package com.clas.liu.myapplication.view.activity.impl;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.clas.liu.myapplication.R;
import com.clas.liu.myapplication.model.entity.user.UserData;
import com.clas.liu.myapplication.presenter.impl.BasePresenter;
import com.clas.liu.myapplication.presenter.impl.EditUserInfoPresenter;
import com.clas.liu.myapplication.view.activity.i.IEditUserInfoActivity;
import com.clas.liu.myapplication.view.util.BitmapUtil;
import com.clas.liu.myapplication.view.util.SaveUtil;
import com.clas.liu.myapplication.view.util.StringUtil;
import com.clas.liu.myapplication.view.widget.CircleImageView;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;

import cn.smssdk.SMSSDK;

/**
 * Created by liu on 2019/5/22.
 */

public class EditUserInfoActivity extends BaseActivity<EditUserInfoPresenter> implements IEditUserInfoActivity,View.OnClickListener {
    private ImageView back;
    private ImageView submit;
    private CircleImageView head;
    private EditText name;
    private EditText age;
    private EditText school;
    private EditText institute;
    private EditText introduction;
    private TextView takePic;
    private TextView choosePic;
    private TextView cancel;
    private ProgressBar loading;
    private AlertDialog.Builder biulder;
    private Dialog choosePicDialog;
    private TextView phone;

    String[] permissionPicture = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    final int[] permissionRequest = {111, 222};
    private Uri tempUri;
    private String str_head;
    private UserData userData = null;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user_info_layout);
        findView();
        init();
        setListener();
    }

    private void setListener() {
        back.setOnClickListener(this);
        submit.setOnClickListener(this);
        head.setOnClickListener(this);
        takePic.setOnClickListener(this);
        choosePic.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    private void init() {
        userData = SaveUtil.<UserData>getFromLocal(getApplicationContext(),"user");
        str_head = userData.getHead();
        initDialog();
        Picasso.with(this).load(userData.getHead()).placeholder(R.mipmap.default_head).into(head);
        name.setText(userData.getName());
        age.setText(String.valueOf(userData.getAge()));
        school.setText(userData.getSchool());
        institute.setText(userData.getInstitute());
        introduction.setText(userData.getIntroduction());
        phone.setText(String.valueOf(userData.getPhone()));
    }

    private void initDialog() {
        choosePicDialog = new Dialog(this, R.style.DialogTheme);
        choosePicDialog.setContentView(View.inflate(this, R.layout.dialog_pic_layout, null));
        Window window = choosePicDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.add_dialog_style);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        takePic = choosePicDialog.findViewById(R.id.tv_take_photo);
        choosePic = choosePicDialog.findViewById(R.id.tv_take_pic);
        cancel = choosePicDialog.findViewById(R.id.tv_cancel);
    }

    private void findView() {
        back = findViewById(R.id.edit_user_back_bt);
        submit = findViewById(R.id.edit_user_submit);
        head = findViewById(R.id.edit_user_head);
        name = findViewById(R.id.edit_user_name);
        age = findViewById(R.id.edit_user_age);
        school = findViewById(R.id.edit_user_school);
        institute = findViewById(R.id.edit_user_institute);
        introduction = findViewById(R.id.edit_user_introduction);
        loading = findViewById(R.id.edit_user_submit_pb);
        phone = findViewById(R.id.edit_user_phone);
    }


    /**
     * 检查权限
     *
     * @param type 类型
     */
    private void checkPermission(int type) {
        String[] permission = {permissionPicture[type]};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int cp2 = ContextCompat.checkSelfPermission(this, permissionPicture[type]);
            if (cp2 != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, permission, permissionRequest[type]);
            } else {
                switch (type) {
                    case 0:
                        getPhoto();
                        break;
                    case 1:
                        takePhoto();
                        break;
                }
            }
        } else {
            switch (type) {
                case 0:
                    getPhoto();
                    break;
                case 1:
                    takePhoto();
                    break;
            }
        }
    }

    /**
     * 打开相机
     */
    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        tempUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        startActivityForResult(intent, permissionRequest[1]);
    }

    /**
     * 从本地图片库选择图片
     */
    private void getPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, permissionRequest[0]);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == permissionRequest[1]) {
                takePhoto();
            } else {
                getPhoto();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        final File croppedImageFile = new File(getFilesDir(), "test.jpg");
        Uri croppedImage = null;
        if (resultCode == RESULT_OK) { // 如果返回码是可以用的
            switch (requestCode) {
                case 222:
                    croppedImage = Uri.fromFile(croppedImageFile);
                    cropPic(croppedImage, tempUri); // 开始对图片进行裁剪处理
                    break;
                case 111:
                    croppedImage = Uri.fromFile(croppedImageFile);
                    cropPic(croppedImage, data.getData()); // 开始对图片进行裁剪处理
                    break;
                case 2:
                    if (data != null) {
                        Bundle bundle = data.getExtras();
                        Bitmap bitmap = null;
                        if (bundle != null) {
                            bitmap = bundle.getParcelable("data");
                        }
                        head.setImageBitmap(bitmap);
                        String filePath;
                        if ((filePath = BitmapUtil.saveImageToGallery(this, bitmap)) == null) {
                            showToast("处理图片失败~ ", Toast.LENGTH_SHORT);
                        }
                        str_head = BitmapUtil.imageToBase64(this,filePath);
                    }

                    break;
            }
        }
    }

    //返回裁剪后的图片
    private void cropPic(Uri croppedImage, Uri tempUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(tempUri, "image/*");//设置要缩放的图片Uri和类型
        intent.putExtra("aspectX", 1);//宽度比
        intent.putExtra("aspectY", 1);//高度比
        intent.putExtra("outputX", 300);//输出图片的宽度
        intent.putExtra("outputY", 300);//输出图片的高度
        intent.putExtra("scale", true);//缩放
        intent.putExtra("return-data", true);//当为true的时候就返回缩略图，false就不返回，需要通过Uri
        intent.putExtra("noFaceDetection", false);//前置摄像头

        startActivityForResult(intent, 2);
    }

    private void checkInputAndPost() {
        String name_str = name.getText().toString();
        String age_str = age.getText().toString();
        String school_str = school.getText().toString();
        String institute_str = institute.getText().toString();
        String introduction_str = introduction.getText().toString();

        if (StringUtil.isEmpty(name_str)) {
            showTips("用户名不能为空！");
            return;
        }
        if (name_str.length() < 2 || name_str.length() > 12) {
            showTips("用户名过短或过长！");
            return;
        }
        if (name_str.contains("管理")) {
            showTips("用户名包含敏感词汇！");
            return;
        }
        if (StringUtil.isEmpty(age_str)) {
            showTips("请输入年龄！");
            return;
        }
        if (!StringUtil.isInteger(age_str)) {
            showTips("输入正确格式的年龄！");
            return;
        }
        userData.setHead(str_head);
        userData.setName(name_str);
        userData.setAge(Integer.parseInt(age_str));
        userData.setSchool(school_str);
        userData.setInstitute(institute_str);
        userData.setIntroduction(introduction_str);
        mPresenter.editUser(userData);
    }

    public void showTips(String tips) {
        if (biulder == null)
            biulder = new AlertDialog.Builder(this);
        biulder.setMessage(tips);
        biulder.setPositiveButton(R.string.alertdialog_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                hideLoadingView();
            }
        });
        biulder.show();
    }

    public void showLoadingView() {
        loading.setVisibility(View.VISIBLE);
        submit.setVisibility(View.GONE);
    }

    public void hideLoadingView() {
        loading.setVisibility(View.GONE);
        submit.setVisibility(View.VISIBLE);
    }

    @Override
    public void failBecauseNetReturn(int code) {
        hideLoadingView();
        showToast(code+"修改失败！",Toast.LENGTH_SHORT);
    }

    @Override
    public void editReturn(UserData userData) {
        showToast("修改成功！",Toast.LENGTH_SHORT);
        SaveUtil.<UserData>saveLocal(this,userData,"user");
        setResult(102);
        finish();
    }

    @Override
    protected EditUserInfoPresenter getPresenter() {
        return new EditUserInfoPresenter(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_user_back_bt:
                this.finish();
                break;
            case R.id.edit_user_submit:
                //数据操作
                showLoadingView();
                checkInputAndPost();
                break;
            case R.id.edit_user_head:
                choosePicDialog.show();
                break;
            case R.id.tv_take_photo:
                //拍照
                checkPermission(1);
                choosePicDialog.dismiss();
                break;
            case R.id.tv_take_pic:
                //从相册获取
                checkPermission(0);
                choosePicDialog.dismiss();
                break;
            case R.id.tv_cancel:
                //
                choosePicDialog.dismiss();
                break;

        }
    }
}
